
pandas 是 Python 生态下用于表格数据处理的库,它提供了一个与 R 中的 DataFrame 类似的数据结构,以及一系列应用在 DataFrame 数据结构上的函数与方法,用于对其进行基本的处理、统计以及可视化操作。
pandas 文档有十分详细的教程,建议阅读。
这里我们展示一个使用 pandas 处理 GFF3 格式文件的例子。
GFF3 是一种表格文件(tsv),它一共有9列是这样定义的:
import pandas as pd
首先让我们将文件读入:
gff3_file = "./data/Homo_sapiens.GRCh38.97.chromosome.16.gene.gff3"
df = pd.read_csv(gff3_file, sep='\t', header=None) # 读取文件,分隔符为 '\t'
df.columns = ["seqid", "source", "type", "start", "end", "score", "strand", "phase", "attributes"]
使用 head 查看一下前 10 行
df.head(10)
查看一下总共有多少行
df.shape
df.shape 返回了一个 tuple 代表这个 DataFrame 的形状: 992 行,9 列
我们还可以做一些基因长度有关的统计:
gene_length = df['end'] - df['start']
gene_length.describe()
我们还可以用pandas内置的函数画一些图:
import matplotlib.pyplot as plt
基因长度分布箱线图:
gene_length.plot.box(label="chr16")
plt.yscale('log')
plt.ylabel("length")
基因的长度与基因相对位置之间的关系:
fig, ax = plt.subplots(figsize=(20, 4))
gene_length.plot(color="#ff5c5c", alpha=0.7)
上面是基因长度的一些基本统计信息(min, max, mean, std, ...)
我们还可以按照信息来源对 df 进行分组(Group),查看一下每种来源的基因有多少
df.groupby('source').count()['seqid']
还可以使用字符串操作将基因的 ENSEMBL ID 从 Attribute 列中取出来
ensids = df.attributes.str.extract("gene:(.*);Name")
然后给原来的 df 添加一列新的值:
df['ENSID'] = ensids
df.head(5)